<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<section>
    <ul>
        <li><a href="http://www.cnblogs.com/rt0d/archive/2011/04/17/2018646.html">图片预加载</a></li>
    </ul>
</section>
<script>
    // 图片预加载
    window.onload = function () {
        preLoadImage('./img/test.png').then((image) => {
            console.log(image.width, image.height);
        })

        Promise
            .all(preloadImages(['./img/test.png', './img/test2.png']))
            .then((images) => {
                images.forEach((image) => {
                    console.log(image.width, image.height);
                })
            })
    };

    function preLoadImage(url) {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.onload = function () {
                // 解决动态图会多次触发onload
                img.onload = null
                resolve(img);
            }
            img.onerror = reject
            img.src = url;
        });
    }

    function preloadImages(urls) {
        return urls.map((url) => {
            return preLoadImage(url)
        })
    }
</script>
</body>
</html>
